package com.zretc.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.entity.Address;
import com.zretc.entity.Cart;
import com.zretc.entity.OrderDetail;
import com.zretc.entity.Orders;
import com.zretc.entity.Product;
import com.zretc.entity.User;
import com.zretc.service.AddressService;
import com.zretc.service.CartService;
import com.zretc.service.OrderDetailService;
import com.zretc.service.OrdersService;
import com.zretc.service.ProductService;
import com.zretc.service.impl.AddressServiceImpl;
import com.zretc.service.impl.CartServiceImpl;
import com.zretc.service.impl.OrderDetailServiceImpl;
import com.zretc.service.impl.OrdersServiceImpl;
import com.zretc.service.impl.ProductServiceImpl;

/**
 * Servlet implementation class OrderDetailServlet
 */
/**
 * @author chenbo 订单表的控制层
 */
@WebServlet("/front/OrderDetailServlet")
public class FrontOrderDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private OrderDetailService orderDetailService = new OrderDetailServiceImpl();
	private CartService cartService = new CartServiceImpl();
	private OrdersService ordersService = new OrdersServiceImpl();
	private AddressService addressService = new AddressServiceImpl();
	private ProductService productService = new ProductServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FrontOrderDetailServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");
		if ("getOrderDetail".equals(op)) {
			// 获取订单基本详情列表
			doGetOrderDetail(request, response);
		} else if ("getOrderProduct".equals(op)) {
			// 获取订单商品详情列表
			doGetOrderProduct(request, response);
		} else if ("insertOrder".equals(op)) {
			// 添加订单
			doInsertOrder(request, response);
		}
	}

	private void doGetOrderDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String orderId = request.getParameter("orderId");
		Orders ordersByOrderId = orderDetailService.getOrdersByOrderId(orderId);
		Gson gson = new Gson();
		String jsonObject = gson.toJson(ordersByOrderId);
		response.setContentType("application/json");
		response.getWriter().write(jsonObject);
	}

	private void doGetOrderProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String orderId = request.getParameter("orderId");
		List<Map<String, Object>> ordersProductByOrderId = orderDetailService.getOrdersProductByOrderId(orderId);
		Gson gson = new Gson();
		String jsonObject = gson.toJson(ordersProductByOrderId);
		response.setContentType("application/json");
		response.getWriter().write(jsonObject);
	}

	private void doInsertOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String[] cartArray = request.getParameterValues("productCheckbox");
		if (cartArray != null) {
			// 订单号 = 订单字母 + 日期 + 四位随机数
			// 订单号字母
			String orderLetter = "A";
			// 日期
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
			String format2 = format.format(date);
			/*
			 * LocalDateTime now = LocalDateTime.now(); DateTimeFormatter ofPattern =
			 * DateTimeFormatter.ofPattern("yyyyMMddhhmmss"); String formatDate =
			 * ofPattern.format(now);
			 */
			// 随机数
			int random = (int) (Math.random() * 1000 + 1000);
			// 拼接
			StringBuilder sborderId = new StringBuilder();
			sborderId.append(orderLetter).append(format2).append(random);
			String orderId = sborderId.toString();
			// 下单时间
			LocalDateTime xia = LocalDateTime.now();
			DateTimeFormatter ofPatternxia = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
			String orderTime = ofPatternxia.format(xia);
			// 订单状态
			Integer orderStatus = 1;
			// 支付方式
			String orderPayMethod = "支付宝在线支付";

			Orders orders = new Orders();
			orders.setOrderId(orderId);
			orders.setOrderTime(orderTime);
			orders.setOrderStatus(orderStatus);

			User user = null;
			Product product = null;
			Integer cartCount = null;
			Float cartPrice = 0.0f;
			Float orderTotalPrice = 0.0f;
			Address addressByUserId = null;
			Integer productId = null;
			// 获取的需要提交订单商品的购物车id 数组
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setOrders(orders);

			for (String string : cartArray) {
				Integer cartId = Integer.valueOf(string);

				Cart cart = cartService.getCartAllBycartId(cartId);
				user = cart.getUser();
				product = cart.getProduct();
				cartCount = cart.getCartCount();
				cartPrice = cart.getCartPrice();
				orderTotalPrice += cartPrice;

				productId = product.getProductId();
				Product productInventoryByProductId2 = productService.getProductInventoryByProductId(productId);
				Integer productInventoryBy2 = productInventoryByProductId2.getProductInventory();
				if (productInventoryBy2 >= cartCount) {
					orderDetail.setOrderDetailCount(cartCount);
					orderDetail.setOrderDetailPrice(cartPrice);
					orderDetail.setOrderDetailStatus(1);
					orderDetail.setProduct(product);
					Integer userId = user.getUserId();
					addressByUserId = addressService.getAddressByUserId(userId);
					if (addressByUserId == null) {
						// 地址状态为o
						// 重定向到购物车界面
						response.sendRedirect("cart.jsp?addressError=error");
					} else {
						productId = product.getProductId();
						Product productInventoryByProductId = productService.getProductInventoryByProductId(productId);
						Integer productInventoryBy = productInventoryByProductId.getProductInventory();
						product.setProductId(productId);
						Integer productInventory = productInventoryBy - cartCount;
						product.setProductInventory(productInventory);
						int updateProductInventoryByProductId = productService
								.updateProductInventoryByProductId(product);
						System.out.println(updateProductInventoryByProductId > 0 ? "修改成功" : "修改失败");
						orderDetailService.insertOrderDetail(orderDetail);
						cartService.deleteCartByCartId(cartId);
					}
				}
			}
			orders.setUser(user);
			orders.setOrderTotalPrice(orderTotalPrice);
			String orderReceiveAddress = addressByUserId.getAddressName();
			String orderReceiveName = addressByUserId.getReceiveName();
			String orderReceivePhone = addressByUserId.getReceivePhone();

			orders.setOrderPayMethod(orderPayMethod);
			orders.setOrderReceiveAddress(orderReceiveAddress);
			orders.setOrderReceiveName(orderReceiveName);
			orders.setOrderReceivePhone(orderReceivePhone);
			ordersService.insertOrder(orders);
			response.sendRedirect("payindex.jsp?orderId=" + orderId + "&orderTotalPrice=" + orderTotalPrice);
		}else {
			response.sendRedirect("cart.jsp");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
